package com.hyzx.qbasic.common.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Created by 黄江华 on 2018/7/24
 * <p>
 * 获取树的子节点
 */

public class TreeNodeUtils {
    private static List<Integer> returnList = new ArrayList<Integer>();

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     */
    public static List<Integer> getChildNodes(List<TreeNode> list, Integer parentId) {
        returnList.clear();

        if (list == null && parentId == null) return Collections.emptyList();

        for (TreeNode node : list) {
            if (node != null && node.getId() != null && parentId.equals(node.getId())) {
                recursionFn(list, node);
            }
        }

        return returnList;
    }

    private static void recursionFn(List<TreeNode> list, TreeNode node) {
        List<TreeNode> childList = getChildList(list, node);// 得到子节点列表
        if (hasChild(list, node)) {// 判断是否有子节点
            returnList.add(node.getId());
            Iterator<TreeNode> it = childList.iterator();
            while (it.hasNext()) {
                TreeNode n = (TreeNode) it.next();
                recursionFn(list, n);
            }
        } else {
            returnList.add(node.getId());
        }
    }

    // 得到子节点列表
    private static List<TreeNode> getChildList(List<TreeNode> list, TreeNode node) {
        List<TreeNode> nodeList = new ArrayList<TreeNode>();
        Iterator<TreeNode> it = list.iterator();
        while (it.hasNext()) {
            TreeNode n = (TreeNode) it.next();
            if (n.getParentId().equals(node.getId())) {
                nodeList.add(n);
            }
        }
        return nodeList;
    }

    // 判断是否有子节点
    private static boolean hasChild(List<TreeNode> list, TreeNode node) {
        return getChildList(list, node).size() > 0 ? true : false;
    }
}
